package com.ileaf.java8.gui;

import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

/**
 * @author Lianlb
 * @date 2019-11-24 13:42
 */
public class Login extends JFrame implements Function {

    private JTextField textPassword;
    private JPanel appPanel;
    private JButton buttonLogin;
    private JLabel textMessage;

    public Login(String title) {
        this.setTitle(title);
        this.setMinimumSize(new Dimension(400, 200));
        this.setLocation(300, 100);
        this.setContentPane(appPanel);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.pack();
        this.setVisible(true);
        createUIComponents();
    }

    @Override
    public void createUIComponents() {
        // TODO: place custom component creation code here
        // 自定义组件已被UI设计器代替
//        appPanel = new JPanel();
//        textPassword = new JTextField();
//        buttonLogin = new JButton();
//        appPanel.setBackground(Color.CYAN);
//        appPanel.add(textPassword);
//        appPanel.add(buttonLogin);
//        textMessage.setSize(100, 20);
        addComponentsAction();
    }

    @Override
    public void addComponentsAction() {
        this.buttonLogin.addActionListener(event -> {
            validatePassword();
        });
        this.textPassword.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                textMessage.setText("");
                if (KeyEvent.VK_ENTER == e.getKeyCode()) {
                    validatePassword();
                }
            }
        });
    }

    private void validatePassword() {
        final String defaultPassword = "m6";
        String password = textPassword.getText();
        if (defaultPassword.equals(password)) {
            System.out.println("success");
            textMessage.setText("验证成功");
            textMessage.setForeground(Color.GREEN);
            // 销毁登录窗口
            dispose();

            // 打开主窗口
            Home home = new Home("系统主页");
            home.pack();
            home.setVisible(true);

        } else {
            System.out.println("failed - " + password);
            textMessage.setText("验证失败...");
            textMessage.setForeground(new Color(187, 44, 14));
        }
    }

}
